package com.leofee.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Logger;

public class MyHttpServletBean extends HttpServlet {

    private static final Logger log = Logger.getLogger("MyHttpServletBean");

    private static final String DEFAULT_CONFIG_PROPERTIES = "application.properties";

    private final Properties properties = new Properties();


    @Override
    public void init() {
        System.out.println(getClass() + " init()!");

        // 加载配置问题
        loadConfig(getServletConfig());

        // 子类继续初始化
        this.onRefresh();

    }

    /**
     * 这是一个模板方法，具体实现由子类决定
     */
    protected void onRefresh() {
        // do nothing
        // let sub class to implement
    }

    /**
     * 加载 web.xml 文件, 读取 {@code init-param}
     *
     * @param servletConfig servletConfig
     */
    private void loadConfig(ServletConfig servletConfig) {

        InputStream contextConfig;
        ClassLoader classLoader = this.getClass().getClassLoader();
        contextConfig = classLoader.getResourceAsStream(servletConfig.getInitParameter("contextConfigLocation"));

        if (contextConfig == null) {
            log.info("contextConfigLocation is not init! use default context config!");
            contextConfig = classLoader.getResourceAsStream(DEFAULT_CONFIG_PROPERTIES);
        }
        try {
            properties.load(contextConfig);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            // 关闭流
            if (contextConfig != null) {
                try {
                    contextConfig.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    Properties getProperties() {
        return this.properties;
    }
}
